//
//  OMAdvertisementViewController.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/4/21.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMAdvertisementViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "YJWebProgressLayer.h"
@protocol JSObjcDelegate <JSExport>

- (void)addShopCart:(NSString *)goodId;
- (void)naviToGoodDetail:(NSString *)goodId;

@end

@interface OMAdvertisementViewController ()
<JSObjcDelegate,UIWebViewDelegate>
@property (nonatomic, strong) YJWebProgressLayer *webProgressLayer;  //  进度条
@property (nonatomic, strong) UIWebView *wkWebView;
@property (nonatomic, assign) NSUInteger loadCount;
@property (nonatomic, strong) JSContext *context;
@property (nonatomic, strong) NSString *currentUrlStr;
@end

@implementation OMAdvertisementViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    ///初始化web容器
    UIWebView *webview = [[UIWebView alloc]init];
    [self.view addSubview:webview];
    webview.delegate = self;
    //webview.UIDelegate = self;
    //webview.navigationDelegate = self;
    _wkWebView = webview;
    //_wkWebView.allowsBackForwardNavigationGestures = YES;
    [webview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@0);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];


    //初始化web加载线条
    _webProgressLayer = [[YJWebProgressLayer alloc] init];
    _webProgressLayer.frame = CGRectMake(0, 42, SM_SCREEN_WIDTH, 2);
    [self.view.layer addSublayer:_webProgressLayer];


    //数据初始化
    [self reload];
    [self startAnimating:YES];
    [self startAnimating:NO];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    _webProgressLayer.frame = CGRectMake(0, CGRectGetMaxY(self.navigationBar.frame)-2 , SM_SCREEN_WIDTH, 2);
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    SMNotificationPost(SM_NOTIFACATION_NEED_CARTITEM_SHOW, nil);
    if (!self.wkWebView.loading) {
        [self reloadDataFromNetWork];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //[self.wkWebView reloadFromOrigin];
}

- (void)reloadDataFromNetWork
{
    [self startAnimating:NO];
    [self reload];
}

- (void)reload
{
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.currentUrlStr]
                                                  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                              timeoutInterval:10];
    [_wkWebView loadRequest:request];
}

- (NSString *)currentUrlStr
{
    if (!_currentUrlStr) {
        _currentUrlStr = self.url;
    }
    return _currentUrlStr;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [_webProgressLayer startLoad];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [OMHUD HUDError:error.localizedDescription];
    [_webProgressLayer finishedLoadWithError:error];
    [self showNetWorkError];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    self.currentUrlStr = request.URL.absoluteString;
    return YES;
}

/**
 webview loadfinished

 @param webView the view parse html content
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_webProgressLayer finishedLoadWithError:nil];
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

    [self clearCache];

    //初始化jscontext
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context[@"APP"] = self;
    self.context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
}



- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.wkWebView stopLoading];

    [self clearCache];
}



/**
 销毁方法
 */
- (void)dealloc
{
    [self clearCache];
    [_webProgressLayer closeTimer];
    [_webProgressLayer removeFromSuperlayer];
    _webProgressLayer = nil;
    _wkWebView = nil;
}



/**
 关闭缓存
 */
- (void)clearCache
{

    self.context[@"APP"] = nil;
    self.context.exceptionHandler = nil;
    self.context = nil;
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}


/**
 内存溢出处理
 */
-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}


/**
 添加购物车

 @param goodId 商品id
 */
- (void)addShopCart:(NSString *)goodId
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [OMHUD HUDLoading:nil];
        OMProduct *product = [OMProduct new];
        product.id = goodId;
        [OMFMDBCartHelper itemAddition:product
                   withButtonAnimation:nil
                            targetView:KTSystemStorageSingleton.badgeView];
    });
}


/**
 跳转到商品详情

 @param goodId 商品id
 */
- (void)naviToGoodDetail:(NSString *)goodId
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NaviPush(@"OMGoodDetailViewController", @{@"productId":goodId});
    });
}

@end
